import {
    message
} from 'ant-design-vue'
import {
    isFunction
} from 'fc-cli-core'

/**mockApi说明：
 * method默认值是post
 * isMock默认值是false，即默认不拦截
 * code默认值是'200'
 * data: 可以是对象
 *       也可以是方法，必须需要通过参数返回不同的数据
 */
const mockApiFun = function ({
    Mock,
    mockApiData = {},
    host = '',
    successCode = '200',
    isMockValue = false,
    methodValue = 'post',
    notNeedMessageTipValue = [],
} = {}) {
    if (!Mock) return;

    for (let api in mockApiData) {
        const url = host ? host + api : api;
        const notNeedMessageTip = notNeedMessageTipValue;
        const {
            method = methodValue,
                isMock = isMockValue,
                data = {},
                code = successCode
        } = mockApiData[api];
        const isFail = code !== successCode;

        if (method == 'get' && isMock) {
            Mock.mock(RegExp(url + ".*"), method, (options) => {
                // console.log('>>> mock-options', options);
                if (!notNeedMessageTip.includes(url)) message.warning('此为mock获取的数据！');
                let returnData = isFail ? {} : data || {}
                if (!isFail && isFunction(data)) returnData = data(options.url)
                return {
                    data: Mock.mock(returnData),
                    code //此状态码必须要返回
                };
            });
        }

        isMock && Mock.mock(url, method, (options) => {
            // console.log('>>> mock-options', options);
            if (!notNeedMessageTip.includes(url)) message.warning('此为mock获取的数据！');
            let returnData = isFail ? {} : data || {}
            if (!isFail && isFunction(data)) returnData = data(JSON.parse(options.body))
            return {
                data: Mock.mock(returnData),
                code //此状态码必须要返回
            };
        });
    }
}


export default mockApiFun;